This assignment teaches linear algebra operations via explicit for loops.
Write a function that accepts as input two rank-3 tensors A_kil and B_ljk, and that calculate the traces T_ij := A_kil B_ljk.
for loopsreshape to calculate the traces also via built-in linear algebra calls, i.e. without for loops@time, for reasonably large matrices)
In [23]:
function trace1{T<:Number}(A::Array{T,3},B::Array{T,3})
if size(A)[1] != size(B)[end] || size(A)[end] != size(B)[1]
throw(BoundsError())
end
imax=size(A)[2]
jmax=size(A)[2]
lmax=size(A)[end]
kmax=size(A)[1]
s=zeros(T,imax,jmax)
for i=1:imax,j=1:jmax,k=1:kmax,l=1:lmax
s[i,j] += A[k,i,l]*B[l,j,k]
end
s
end
Out[23]:
In [ ]:
function trace
In [33]:
A = reshape(collect(1:27),3,3,3);
B = reshape(collect(28:(28+27-1)),3,3,3);
In [35]:
@time trace1(A,B)
Out[35]:
In [22]:
zeros(Float64,2,2)[1,1]
Out[22]:
In [21]:
for i=1:2,j=1:2
println(i+j)
end
In [ ]: